package com.eightbears.beboy.adapter;

import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.eightbears.beboy.R;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.view.gif.AnimatedGifDrawable;
import com.eightbears.beboy.base.view.gif.AnimatedImageSpan;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.entity.PostCommentsEntity;
import com.makeramen.roundedimageview.RoundedImageView;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.eightbears.beboy.R.id.iv_vip;


/**
 * Created by Bao on 2016/12/7.
 * 评论列表页面
 */
public class PostCommentListAdapter extends BaseQuickAdapter<PostCommentsEntity.PostComment, BaseViewHolder> {


    private JSONArray faceJson;
    private boolean subCommentExist = false;

    private OnClickSubCommentItemListener mOnClickSubCommentItemListener;
    private OnLongClickSubCommentItemListener mOnLongClickSubCommentItemListener;


    public PostCommentListAdapter() {
        super(R.layout.item_post_comment, null);
    }

    // 子评论单击
    public interface OnClickSubCommentItemListener {
        void onSubCommentClick(BaseQuickAdapter baseViewHolder, View view, int i, PostCommentsEntity.PostComment comment);
    }

    public void setOnSubCommentClickListener(OnClickSubCommentItemListener listener) {
        this.mOnClickSubCommentItemListener = listener;
    }

    // 子评论长按
    public interface OnLongClickSubCommentItemListener {
        void onLongSubCommentClick(BaseQuickAdapter baseViewHolder, View view, int i, PostCommentsEntity.PostComment comment);
    }

    public void setLongOnSubCommentClickListener(OnLongClickSubCommentItemListener listener) {
        this.mOnLongClickSubCommentItemListener = listener;
    }

    @Override
    protected void convert(final BaseViewHolder baseViewHolder, PostCommentsEntity.PostComment postComment) {
        TextView tv_comment = baseViewHolder.getView(R.id.tv_comment);
        baseViewHolder.setText(R.id.tv_nickname, postComment.getUser().getNickname())
                .setText(R.id.tv_date, CommonUtils.TimeStamp2Date(postComment.getCommented_at(), "yyyy-MM-dd"))
                .addOnClickListener(R.id.iv_user_head).addOnClickListener(R.id.tv_repost_user);
        if (checkGifExist(postComment.getComment())) {
            tv_comment.setText(handler(tv_comment, postComment.getComment()));
        } else {
            tv_comment.setText(postComment.getComment());
        }
        CommonUtils.loadImageView(mContext, postComment.getUser().getCover(),
                R.mipmap.default_head, (RoundedImageView) (baseViewHolder.getView(R.id.iv_user_head)));

        showView4Status(postComment, baseViewHolder);

        if (subCommentExist) {
            initSubCommentAdapter(baseViewHolder, postComment);
        }

    }

    //
    private void initSubCommentAdapter(BaseViewHolder baseViewHolder, final PostCommentsEntity.PostComment comment) {
        RecyclerView rl_sub_comment = baseViewHolder.getView(R.id.rl_sub_comment);
        rl_sub_comment.setLayoutManager(new MyLinearLayoutManager(mContext));
        rl_sub_comment = baseViewHolder.getView(R.id.rl_sub_comment);
        SubPostAdapter subPostAdapter = new SubPostAdapter(comment.getSub_comments().getList());
        rl_sub_comment.setAdapter(subPostAdapter);
        subPostAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                mOnClickSubCommentItemListener.onSubCommentClick(adapter, view, position, comment);
            }
        });
        subPostAdapter.setOnItemChildLongClickListener(new OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                mOnLongClickSubCommentItemListener.onLongSubCommentClick(adapter, view, position, comment);
                return true;
            }
        });
    }

    private class SubPostAdapter extends BaseQuickAdapter<PostCommentsEntity.SubPostComment, BaseViewHolder> {

        private LinearLayout ll_reply_text;
        private TextView tv_line;

        SubPostAdapter(List<PostCommentsEntity.SubPostComment> data) {
            super(R.layout.item_sub_comment, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, PostCommentsEntity.SubPostComment item) {
            helper.setText(R.id.tv_supcomment_usertx, item.getComment())
                    .setText(R.id.tv_supcomment_user, item.getUser().getNickname());
            helper.addOnClickListener(R.id.ll_post_comment_comment)
                    .addOnLongClickListener(R.id.ll_post_comment_comment);
            ll_reply_text = helper.getView(R.id.ll_reply_text);
            tv_line = helper.getView(R.id.tv_line);

            if (null != item.getReply_user() &&
                    !item.getReply_user().getUser_id().equals(SPUtil.getUser().getData().getUser_id())) {
                ll_reply_text.setVisibility(View.VISIBLE);
                tv_line.setVisibility(View.GONE);
                helper.setText(R.id.tv_reply_name, item.getReply_user().getNickname() + ":");
            } else {
                ll_reply_text.setVisibility(View.GONE);
                tv_line.setVisibility(View.VISIBLE);
            }
        }
    }

    private void showView4Status(PostCommentsEntity.PostComment postComment,
                                 BaseViewHolder baseViewHolder) {
        ImageView iv_vip = baseViewHolder.getView(R.id.iv_vip);
        ImageView iv_level = baseViewHolder.getView(R.id.iv_level);

        //判断是否有子评论，显示子评论
        if (postComment.getSub_comments().getList().size() > 0) {
            baseViewHolder.setVisible(R.id.ll_item_post_comment, true);
            subCommentExist = true;
        } else {
            baseViewHolder.setVisible(R.id.ll_item_post_comment, false);
            subCommentExist = false;
        }

//        if (postComment.getUser().getVip_level() > 0) {
//            baseViewHolder.setVisible(iv_vip, true);
//        } else {
//            baseViewHolder.setVisible(iv_vip, false);
//        }

        if (postComment.getUser().getVip_level() == 1) {
            iv_vip.setVisibility(View.VISIBLE);
            iv_vip.setImageResource(R.mipmap.icon_new_vip1);
        } else if (postComment.getUser().getVip_level() == 2) {
            iv_vip.setVisibility(View.VISIBLE);
            iv_vip.setImageResource(R.mipmap.icon_new_vip2);
        } else {
            iv_vip.setVisibility(View.GONE);
        }

        if (postComment.getPoints() != null) {
            if (postComment.getPoints().getLevel() == 1) {
                iv_level.setImageResource(R.mipmap.icon_level_one);
            } else if (postComment.getPoints().getLevel() == 2) {
                iv_level.setImageResource(R.mipmap.icon_level_two);
            } else if (postComment.getPoints().getLevel() == 3) {
                iv_level.setImageResource(R.mipmap.icon_level_three);
            } else if (postComment.getPoints().getLevel() == 4) {
                iv_level.setImageResource(R.mipmap.icon_level_four);
            } else if (postComment.getPoints().getLevel() == 5) {
                iv_level.setImageResource(R.mipmap.icon_level_five);
            }
            iv_level.setVisibility(View.VISIBLE);
        }


    }

    private boolean checkGifExist(String message) {
        String regex = "(\\[[a-z]*[^\\[\\u0000-\\u007F\\]]+\\])";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(message);
        if (m.find()) {
            return true;
        } else {
            return false;
        }
    }

    // 对文字处理后显示
    private SpannableStringBuilder handler(final TextView gifTextView, String content) {
        if (faceJson == null) {
            faceJson = CommonUtils.getFromAssets2Json("face/face.json", mContext);
        }
        SpannableStringBuilder sb = new SpannableStringBuilder(content);
        String regex = "(\\[[a-z]*[^\\[\\u0000-\\u007f\\]]+\\])";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(content);
        while (m.find()) {
            for (int i = 0; i < faceJson.length(); i++) {
                try {
                    JSONArray arr = (JSONArray) faceJson.get(i);
                    String faceTemp = arr.get(1).toString();
                    if (faceTemp.equals(m.group())) {
                        String gif = "face/" + arr.get(0);
                        InputStream is = mContext.getAssets().open(gif);
                        sb.setSpan(new AnimatedImageSpan(new AnimatedGifDrawable(is, new AnimatedGifDrawable.UpdateListener() {
                            @Override
                            public void update() {
                                gifTextView.postInvalidate();
                            }
                        })), m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        is.close();
                    }
                } catch (JSONException | IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb;
    }
}
